package Survey;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class DModuleMultipleChoice extends DisplayModule {

	private static final long serialVersionUID = -1121385660737262451L;

	AbstractButton other;
	JTextField otherField;
	ButtonGroup group;
	Vector<JCheckBox> group2;

	public DModuleMultipleChoice(SurveyParameters data, int index){
		super(data, index);

		center.setLayout(new GridLayout(data.dimensions[SurveyParameters.HEIGHT], data.dimensions[SurveyParameters.WIDTH]));

		group = new ButtonGroup();
		group2 = new Vector<JCheckBox>();
		
		for(String[] sa : data.options){
			for(String a: sa){
				AbstractButton working;

				if(data.type == SurveyParameters.SINGLE_CHOICE){
					working = new JRadioButton(a);
					group.add(working);
				}else{
					working = new JCheckBox(a); 
					group2.add((JCheckBox)working);
				}

				working.setOpaque(true);
				working.setBackground(Color.white);
				if(a.startsWith("xx")){
					working.setText(a.substring(2));
					JPanel temp = new JPanel();
					temp.setLayout(new BoxLayout(temp, BoxLayout.X_AXIS));
					other = working;
					otherField = new JTextField(10);
					otherField.setMaximumSize(otherField.getPreferredSize());
					
					temp.setOpaque(true);
					temp.setBackground(Color.white);
					temp.setLayout(new BoxLayout(temp, BoxLayout.X_AXIS));
					temp.add(working);
					temp.add(otherField);
					temp.add(Box.createHorizontalGlue());

					center.add(temp);
				}else{
					center.add(working);
				}
			}
		}

		setMaximumSize(new Dimension(DisplayGui.MODULEWIDTH, (20 + top.getPreferredSize().height + center.getPreferredSize().height)));
		validate();
		repaint();
	}

	public String[] getData() {
		
		int i = 0;
		Vector<String> holder = new Vector<String>();
		for(Enumeration<AbstractButton> e = group.getElements(); e.hasMoreElements();i++){    
            JRadioButton working = ((JRadioButton)e.nextElement());
            if(working.isSelected()){
                if(!working.equals(other)){
                	holder.add(working.getText());
                }else{
                	holder.add(working.getText() + ":" + otherField.getText());
                }
                continue;
            }
        }
		
		for(JCheckBox jc : group2){
			if(jc.isSelected()){
				if(!jc.equals(other)){
                	holder.add(jc.getText());
                }else{
                	holder.add(jc.getText() + ":" + otherField.getText());
                }
			}
		}
		
		
		if(holder.size() == 0){
			return null;
		}
		
		String[] retVal = new String[holder.size()];
		for(int j = 0; j < retVal.length; j++){
			retVal[j] = holder.get(j);
		}
		return retVal;
	}
}